/*
场所
*/
var menuItem=new Array();
/*
初始化加载折线图和表格
*/
$(document).ready(function () {
	initDateObj();
	siteKey = $("#siteKey").val();
	type = $("#hdtype").val();
	if(siteKey=="" || type==""){
		var str = "<div class='em100 whitediv' id='zhanwushuju'><div class='em25'></div><div class='backyellow'>&nbsp;&nbsp;暂无数据！请选择场所</div></div>"
		$("#myForm .widthall .chartdiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .xiangxidiv").children("div[id!='zhanwushuju']").hide();
		$("#myForm .widthall .chartdiv").html(str);
		$("#myForm .widthall .xiangxidiv").html(str);
		
	}else{
		getIndexOrder();
	}
	
})

var dateO ;
 var dateO1 ;
//初始化时间段时间控件
function initDateObj() {
	var endDate=new Date();//当前时间
	endDate=endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();
	var startDate=(new Date());
	startDate.setDate(startDate.getDate()-30);//前一个月时间
	startDate=startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();

	var startMonth=new Date();
	startMonth.setDate(startMonth.getDate()-90);
	startMonth=startMonth.getFullYear()+"-"+(startMonth.getMonth()+1)+"-"+startMonth.getDate();
	
	var startYear=new Date();
	startYear.setFullYear(startYear.getFullYear()-3);
	startYear=startYear.getFullYear()+"-"+(startYear.getMonth()+1)+"-"+startYear.getDate();
	
    var dateObj = {
        theme: 'ta', // 日期选择器TA主题
        autoCommit: false, //自动提交，完成日期初始化，以及图表的展示拉取
        isTodayValid: true,
        startDate: startDate,
        endDate: endDate,
        needCompare: true,
        startCompareDate: '',
        endCompareDate: '',
        singleCompare: false,
        defaultText: ' 至 ',
        autoSubmit: false,
        shortOpr: false,
        target: 'datePicker',
        calendars: 2,
        inputTrigger: 'input_trigger',
        compareCheckboxId: false,
        success: function (obj) {
            if (($("#txtspan").val().split("_"))[1] == "0" || $("#needCompare").val() == "1")//处于如期选择框时
            {
                loadChart($("#hdtype").val());
            }
        }
    };
   dateO = new pickerDateRange("date", dateObj);

}

//日时间控件
function hourDateObj(){
	$("#shijianduibi").children().remove();
	var datediv = "<div id='div_date' class='nocheckoption' style='cursor:pointer;'  onclick=getspan('day_0')>"+
       "<span id='date' onclick=getspan('day_0')>2015-5-1</span>"+
   		"</div>"
	$("#shijianduibi").html(datediv);
	var endDate=new Date();//当前时间
	endDate=endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();
	var dateObj1 = {
	    theme: 'ta', // 日期选择器TA主题
	    autoCommit: false, //自动提交，完成日期初始化，以及图表的展示拉取
	    isTodayValid: true,
	    startDate: endDate,
	    endDate: endDate,
	    needCompare: true,
	    startCompareDate: '',
	    endCompareDate: '',
	    singleCompare: false,
	    defaultText: ' 至 ',
	    autoSubmit: false,
	    shortOpr: true,
	    target: 'datePicker',
	    calendars: 2,
	    isSingleDay: true,
		singleCompare: false,
//		dayRangeMax: 1,
	    inputTrigger: 'input_trigger',
	    compareCheckboxId: false,
	    success: function (obj) {
	        if (($("#txtspan").val().split("_"))[1] == "0" || $("#needCompare").val() == "1")//处于如期选择框时
	        {
	            loadChart($("#hdtype").val());
	        }
	    }
	};
   new pickerDateRange("date", dateObj1);
}
//日周月年控件
function rizhouDateObj(){
		$("#shijianduibi").children().remove();
	var datediv = "<div id='div_date' class='nocheckoption' style='cursor:pointer;'  onclick=getspan('day_0')>"+
       "<span id='date' onclick=getspan('day_0')>2015-5-1</span>"+
   		"</div>"
	$("#shijianduibi").html(datediv);
		var endDate=new Date();//当前时间
		endDate=endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate();
		var startDate=(new Date());
		startDate.setDate(startDate.getDate()-30);//前一个月时间
		startDate=startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();
	
		var startMonth=new Date();
		startMonth.setDate(startMonth.getDate()-90);
		startMonth=startMonth.getFullYear()+"-"+(startMonth.getMonth()+1)+"-"+startMonth.getDate();
		
		var startYear=new Date();
		startYear.setFullYear(startYear.getFullYear()-3);
		startYear=startYear.getFullYear()+"-"+(startYear.getMonth()+1)+"-"+startYear.getDate();
	   var dateObj = {
        theme: 'ta', // 日期选择器TA主题
        autoCommit: false, //自动提交，完成日期初始化，以及图表的展示拉取
        isTodayValid: true,
        startDate: startDate,
        endDate: endDate,
        needCompare: true,
        startCompareDate: '',
        endCompareDate: '',
        singleCompare: false,
        defaultText: ' 至 ',
        autoSubmit: false,
        shortOpr: false,
        target: 'datePicker',
        calendars: 2,
        inputTrigger: 'input_trigger',
        compareCheckboxId: false,
        success: function (obj) {
            if (($("#txtspan").val().split("_"))[1] == "0" || $("#needCompare").val() == "1")//处于如期选择框时
            {
                loadChart($("#hdtype").val());
            }
        }
    };
  new pickerDateRange("date", dateObj);
}
 
 function loadPaiHang(siteId, type) {}
/*
加载折线图表取XY轴
*/
function  getXY(timeType_table,result,type) {
	var xsisRe="";
	var dataRe="";
	var indexName = getOrderField(type);
	if(timeType_table=="day"||timeType_table=="hour"){
		for(var i=0;i<result.length;i++){
			xsisRe=xsisRe + result[i].datatime+",";
			dataRe=dataRe + getObjectVlue(result[i],indexName)+",";
		}
	}else if(timeType_table=="week"){
		for(var i=0;i<result.length;i++){
			xsisRe=xsisRe + result[i].year+"."+result[i].week +",";
			dataRe=dataRe + getObjectVlue(result[i],indexName)+",";
		}
	}else if(timeType_table=="month"){
		for(var i=0;i<result.length;i++){
			xsisRe=xsisRe + result[i].year+"."+result[i].month +",";
			dataRe=dataRe + getObjectVlue(result[i],indexName)+",";
		}
	}else{
		for(var i=0;i<result.length;i++){
			xsisRe=xsisRe + result[i].year +",";
			dataRe=dataRe + getObjectVlue(result[i],indexName)+",";
		}
	}
	xsisRe=xsisRe.substring(0,xsisRe.length-1);
	dataRe=dataRe.substring(0,dataRe.length-1);
	var result =new Array();
	result.push(xsisRe);
	result.push(dataRe);
	return result
}

/*
加载折线图表
*/
 function loadChart(type) {
	 showLoading();
	//指标显示底色
	 zhibiaoCss(type)
	 //获取指标名称
     var indexname = array[parseInt(type)];
	//获取指标单位
	 var zhibiaodanwei = arraydanwei[parseInt(type)];
     var from = $('#startDate').val();
     var to = $('#endDate').val();
     siteIds=$('#siteKeys').val();
     var tubiao = "tubiao1";
     var spancss = $("#txtspan").val();
     shijianCss(spancss);
     /**如果spancss为day_0需要判断timeModel的值，如果是day则设置为day_0；
      如果是week则设置为week_0；如果是month则设置为month_0；如果是year
      则设置为year_0；*/
	 if($("#timeModel").val()=="hour"&&spancss=="day_0"){
     	$("#txtspan").val("hour_0");
 	 }else if($("#timeModel").val()=="day"&&spancss=="day_0"){
     	$("#txtspan").val("day_0");
 	 }else if($("#timeModel").val()=="week"&&spancss=="day_0"){
 		 $("#txtspan").val("week_0");
 	 }else if($("#timeModel").val()=="month"&&spancss=="day_0"){
 		 $("#txtspan").val("month_0");
 	 }else if($("#timeModel").val()=="year"&&spancss=="day_0"){
 		 $("#txtspan").val("year_0");
 	 }
     var span = $("#txtspan").val();
     var myChart = echarts.init(document.getElementById(tubiao));
   	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "getComparativeAnalysis",
   		data: { from: from, to: to, type: type, span: span, siteIds: siteIds },
   		async: true,
   		success : function(ret) {
   			//图表的位置
   			var titleOffens = "";
   			var dataZoomY = "";;
   			var toolboxX = "";
   			var width = $("#tubiao1").width();
			var height = $("#tubiao1").height();
			titleOffens = width*7.6/100;
			dataZoomY = height*(1-8/100);
			toolboxX = width*80/100;
			var legendY = height*4.5/100;
			var toolboxY = height*0.5/100;
			//获取当前时间
			var date = new Date;
			var today =  timeFormat(date);
			//保存图片的名称
			var toolboxName = $("#titles").val()+'-趋势分析'+today;
			var stadubiao = ret.stadubiao;
			var endtubiao = ret.endtubiao;
			var siteN = ret.siteN;
			var siteTypeNames = ret.siteTypeNames;
   			var timeType_table = ret.timeType_table;//返回的日周月年
   			var  result = ret.result;//返回数据集
   			var  Table = ret.loadTable;//返回数据集
   			var xsisRe="";//X轴
   			var dataRe="";//数据线
   			var titName="";//表题
   			
   			var timeModleName = "";
   			if(timeType_table == "hour"){
				timeModleName = "时";
			}else if(timeType_table == "day"){
   				timeModleName = "日";
   			}else if(timeType_table == "week"){
   				timeModleName = "周";
   			}else if(timeType_table == "month"){
   				timeModleName = "月";
   			}else if(timeType_table == "year"){
   				timeModleName = "年";
   			}
   			
   			for(var site=0;site<result.length;site++){
   				var redata=result[site];
   				var siteName=redata.siteName
   				var siteData=redata.data
   				var resultXY=getXY(timeType_table,siteData,type);
   				xsisRe=resultXY[0];
   			}
   			var xsis = xsisRe.split(","); 
   			
   			/**
   			 * 横坐标只有一个值时显示为柱状图，柱状宽度最大为40
   			 */
   			var lineType = 'line';
   			if(xsis.length ==1){
   				lineType = 'bar';
   			}else{
   				lineType = 'line';
   			}
   			var barMaxWidthn = 40;
   			
   			for(var site=0;site<result.length;site++){
   				var redata=result[site];
   				var siteName=redata.siteName
   				titName=titName+siteName+",";
   				var siteData=redata.data
   				var resultXY=getXY(timeType_table,siteData,type);
   				xsisRe=resultXY[0];
   				datay=resultXY[1];
   				var markLinePrecision = 0;
   					dataRe=dataRe+"{name:'"+siteName+"',markLine: {precision:markLinePrecision, data: [{type: 'average',name: '平均值'}]},type:lineType,smooth: smoothType,barMaxWidth:barMaxWidthn,itemStyle:{ normal:{color:'#feab41'}},itemStyle:{normal:{label:{show:"+getShow(xsis)+",position:'top'}}},data:[" +datay + "]}"+",";
   			}
   			var titName=titName.split(",")
   			var data = eval("["+dataRe+"]");
			
			$("#tubiao1shuoming1").html("各场所指标"+"趋势对比");
			if(timeType_table=='week'){
				$("#tubiao1shuoming2").html(getTiptollmon(stadubiao)+(endtubiao==null?'':"~"+getTiptollsun(endtubiao)));
				
   				titContext="数据说明："+"各场所指标"+"趋势对比"+"\n"
					+"时间范围："+getTiptollmon(stadubiao)+(endtubiao==null?'':"~"+getTiptollsun(endtubiao))+"\n"
					+"场所名称："+siteTypeNames+"\n"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
			}else{
				$("#tubiao1shuoming2").html(stadubiao+(endtubiao==null?'':"~"+endtubiao));
				titContext="数据说明："+"各场所指标"+"趋势对比"+"\n"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"\n"
					+"场所名称："+siteTypeNames+"\n"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
   			}
			$("#tubiao1shuoming3").html(siteTypeNames);
			$("#tubiao1shuoming4").html(indexname+"（"+zhibiaodanwei+"）");
			
			/*
			数据说明
			*/
			var biaogeshuomingContext = "数据说明："+"各场所指标"+"趋势对比"+"<br/>"
					+"时间范围："+stadubiao+(endtubiao==null?'':"~"+endtubiao)+"<br/>"
					+"场所名称："+siteTypeNames+"<br/>"
					+"指标名称："+indexname+"（"+zhibiaodanwei+"）";
   			$("#biaogeshuoming").html(biaogeshuomingContext);
			
			
   			var  option = {
   			
			title : {
				show:false,
		      text: titContext,
		      y:'bottom',
		      x:titleOffens,
		      textStyle:{
		        fontSize: 12,
   		        color: '#666',
				fontFamily:'微软雅黑, 兰亭细黑, 宋体',
   		        fontWeight:'normal'
		    	}		
     		 },		
     		 dataZoom: {
    		        show: true,
    		        y:dataZoomY 
    		    },		
			tooltip: {
				trigger: 'axis',
				backgroundColor: 'rgba(0,0,0,0.7)',
				position: function(p) {
					return [p[0] + 10, p[1] - 10];
				},
				formatter: function(params, ticket, callback) {
					var returnstr = "";
					var time = params[0][1];
					if (timeType_table == 'week') {
						returnstr = "<tr>"+getTiptollTime(time)+"</tr>";
					}else{
						returnstr = "<tr>"+time+"</tr>";
					}
					for (var i=0; i<params.length; i++) {
						var a = params[i][0];
						
						
						var c = params[i][2];
						c = addKannma(c);
						if (c == '') {
							c = 0;
						}
						returnstr = returnstr +  "<tr><td>"+a+"："+"</td><td style='text-align: right;'>"+c+"</td></tr>";
						
					};
					var table = "<table>"+returnstr+"</table>"
					return table;
				}
			},
   			legend: {
   		        data:titName,
   		        y:legendY
   		    },
   			grid:{
   				x:'7.6%',
   				y:'11%',
   				y2:'15%',
   				borderWidth: gridBorderWidth,
				borderColor:'#EEE'
   			},
		    toolbox: {
		        show : true,
		        feature : {
		            mark : {show: true},
		            magicType : {show: true, type: ['line', 'bar']},
		            restore : {show: true},
		            saveAsImage : {show: true,name:toolboxName}
		        },
		        x:toolboxX,
		        y:toolboxY
		    },
		    calculable : true,
		    xAxis : [
		        {
		        	name : '日期'+'('+timeModleName+')',
		        	boundaryGap: true,//两端空白策略
		        	allowDecimals :true,//使用小数
		            type : 'category',
		            splitLine: {show: xAxisSplitLine,
					lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		            splitArea:{
						show:xAxissplitArea,
						areaStyle:{
								color: [
						        'rgba(250,250,250,0.1)',
						        'rgba(200,200,200,0.1)']
							}
					},
		            data : xsis,
		            axisTick:{
						show:true,
						interval:0
					}
		        }
		    ],
		    yAxis : [
		        {
					axisLabel:{
						formatter: function (value) {
		            		if(value > 10000){
		            			return (value/10000)+'万';
		            		}else{
		            			return value + '';
		            		}
						}
					},
		        	splitLine: {
						show: yAxisSplitLine,
						lineStyle:{
							 color: ['#EEE'],
							
						}},//不显示竖线
		        	splitArea:{
						show:yAxissplitArea,
						areaStyle:{
							color: [
					        'rgba(250,250,250,0.1)',
					        'rgba(200,200,200,0.1)']
						}
					},
		        	name : indexname+'('+zhibiaodanwei+')',
		            type : 'value'
		        }
		    ],
		    series : data
		};
   		// 动态添加默认不显示的数据
   			myChart.on(echarts.config.EVENT.LEGEND_SELECTED, function(param) {
   				console.log(param);
   			});
   			//改变窗口大小使图标自适应窗口显示
   			window.onresize = function () {
   				myChart.resize();
   			}
   			myChart.setOption(option);
   			//加载表格
   			loadTable1(Table);
   			hideLoading();
   			
   		},
		error : function(mm, a, b, c, d, e) {
				hideLoading();
				alert("服务器好像开小差了，刷新一下试试吧！");
			}
   	})
}

//加载图表
 function loadTable1(result) {
             $("#hdtable").val(result);
			 /**
			  * 测试
			  */
			 $("#datatable").html(result);
			showtable(1);
 }


function ifFromsubmit(){
	var  siteKey=$('#siteKey').val();
	var onSelectSite=$('#onSelectSite').val();
	$('#siteString').val(siteKey);
	if(siteKey==null||siteKey==""){
	$('#siteSelectForm').submit();
	}
}
function fromsubmit(){
	var  siteKey=$('#siteKey').val();
	var onSelectSite=$('#onSelectSite').val();
	$('#siteString').val(siteKey);
	$('#siteSelectForm').submit();
}	

function checked(id,siteId){
	var item= menuItem[id];
	if(item==null||""==item){
		
//			如果已经有7个就不能再checked
		var siteNum=0;
		for(var n=0;n<menuItem.length;n++){
			if(menuItem[n]==null||""==menuItem[n]){
			}else{
				siteIds=siteIds+menuItem[n]+",";
				siteNum++;
			}
		}
		if(siteNum>6){
			alert("提示","广场数超出上限");
			return;
		}
		
		$("#"+id).removeClass("checkbox");
	 	$("#"+id).addClass("checkboxed");
	 	menuItem[id]=siteId;
	}else{
		$("#"+id).removeClass("checkboxed");
	 	$("#"+id).addClass("checkbox");
	 	menuItem[id]="";
	}
	var siteIds="";
	for(var n=0;n<menuItem.length;n++){
		if(menuItem[n]==null||""==menuItem[n]){
		}else{
			siteIds=siteIds+menuItem[n]+",";
		}
	}
	siteIds=siteIds.substring(0, siteIds.length-1);
	$('#siteKeys').val(siteIds);
	 loadChart($("#hdtype").val());
}
	
function extbkboxnar(){
	var fadeSpeed=1;
	var menu1 = document.getElementById("menu1");
	if (menu1.style.display == "block"){
			menu1.style.display = "none";
			$('#fl_menu .label').fadeTo(fadeSpeed, 1);
			$("#fl_menu .menu").fadeIn(fadeSpeed);
			$("#fl_menu").css("width","15%")
	}else{
			menu1.style.display = "block";
			$('#fl_menu .label').fadeTo(fadeSpeed, 0.75);
			$("#fl_menu .menu").fadeOut(fadeSpeed);
			$("#fl_menu").css("width","7%")
	}		
}
	
/*
只对比7个场所
*/
function initCompSite(siteIds){
	var siteIdstr=siteIds;
	var siteKeys="";
	if(siteIds!=""){
		var siteArr=siteIdstr.split(",");
		for(var site in siteArr ){
			if(site>6){
				break;
			}
			siteKeys=siteKeys+siteArr[site]+',';
		}
	}
	if(siteKeys!=""){siteKeys=siteKeys.substring(0, siteKeys.length-1);}
	$("#siteKeys").val(siteKeys);
	
	var str="";
	var siteIds=siteIds;
	$.ajax( {
   		type : "GET",
   		contentType:"application/json",
   		dataType : 'json',
   		url: "getComparativeSiteName",
   		data: {siteIds:siteIds},
   		async: true,
   		success : function(ret) {
   			for(var n=0;n<ret.length;n++){
   				if(n<7){
	   				str=str+"<div class='menu_item' id='brand-"+n+" rel='0'><div title='1231212' id='"+n+"' onclick=checked("+n+",'"+ret[n].siteId+"') class='floatleft checkboxed width130'><div >"+ret[n].siteName+"</div></div></div>";
	   				menuItem[n]=ret[n].siteId;
   				}else{
   					str=str+"<div class='menu_item' id='brand-"+n+" rel='0'><div title='1231212' id='"+n+"' onclick=checked("+n+",'"+ret[n].siteId+"') class='floatleft checkbox width130'><div >"+ret[n].siteName+"</div></div></div>";	
   					menuItem[n]="";
   				}
   			}
   			$("#narrowbox").html(str);
   		},
		error : function(mm, a, b, c, d, e) {
				hideLoading();
				alert("服务器好像开小差了，刷新一下试试吧！");
			}
 	})
	
	
}
	
